<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="id">

        <el-select
          v-model="queryParams.id"
          clearable
          :filter-method="hospitalFilter"
          remote
          filterable
          placeholder="请选择产品名称"
          class="!w-240px"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.id"
            :label="item.fullName"
            :value="item.id"
          />
        </el-select>
        <!-- <el-tree-select
          v-model="queryParams.id"
          :data="supplierList"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择产品名称"
          class="!w-240px"
        /> -->
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>



   <!-- 列表 -->
   <ContentWrap>
    <el-table v-loading="loading" :data="list"  :stripe="true" :show-overflow-tooltip="true"  >
 
      <el-table-column label="条码" align="center" prop="barCode" />
      <el-table-column label="名称" align="center" prop="name" width="120px"/>
      <el-table-column label="规格" align="center" prop="standard" width="100px"/>
      <el-table-column label="分类" align="center" prop="categoryName" width="80px"/>
      <el-table-column label="单位" align="center" prop="unitName" width="100px"/>
      <el-table-column label="是否挂接" align="center" prop="isHooking"  width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_IS_QUANTITY" :value="scope.row.isHooking" />
        </template>
      </el-table-column>
      <el-table-column
        label="采购价格"
        align="center"
        prop="purchasePrice"
        :formatter="erpPriceTableColumnFormatter"
         width="100px"
      />
      <el-table-column
        label="销售价格"
        align="center"
        prop="salePrice"
        :formatter="erpPriceTableColumnFormatter"
         width="100px"
      />
      <el-table-column
        label="最低价格"
        align="center"
        prop="minPrice"
        :formatter="erpPriceTableColumnFormatter"
        width="100px"
      />
      <el-table-column label="状态" align="center" prop="status"  width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="是否带量" align="center" prop="isQuantity"  width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_IS_QUANTITY" :value="scope.row.isQuantity" />
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['spd:relationship:update']"
          >
            挂接
          </el-button>
          <!-- <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:relationship:delete']"
          >
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <RelationshipForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import debounce from 'lodash/debounce'
import { erpPriceTableColumnFormatter } from '@/utils'
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { RelationshipApi, RelationshipVO } from '@/api/spd/relationship'
import RelationshipForm from './RelationshipForm.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import { ProductApi, ProductVO } from '@/api/spd/product/product'

/** 物料供应商关联 列表 */
defineOptions({ name: 'Relationship' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const supplierList = ref<ProductVO[]>([]) // 供应商列表
const list = ref<ProductVO[]>([]) // 列表的数据
const loading = ref(true) // 列表的加载中
let porductList= [] // 医院列表
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name:undefined,
  fullName:undefined,
  id: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中



/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductApi.pagesForRelation(queryParams)
    console.log("2222",data.list)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/**
 * 键入监听方法
 */
 const hospitalFilter =(params)=> {
  //判断键入是否有值
  if(params!==""){
    //有值调用防抖方法
    debouncedSearch(params)
  }else{
    //没有键入值，集合为空
    supplierList.value=[]
  }
}
/**
 * 根据键入的值查询产品列表
 */
const productLists=async(params)=>{
  // 加载产品列表
  const supplierData = await ProductApi.getProductSimpleLists(params)
  supplierList.value = handleTree(supplierData, 'id')
}

 // 创建一个防抖函数来处理搜索操作
 const debouncedSearch =debounce((params,delay = 500) => { 
      //定义等待时间
      const timer = ref() 
      // 模拟异步数据获取（例如API调用）
      if(timer.value){
          //清除等待时间
          clearTimeout(timer.value); 
        }
      //等待时间赋值
      timer.value = setTimeout(async() => {
        //调用后端根据键入的值查询产品列表方法
        productLists(params)
      }, delay); // 延迟500毫秒以模拟网络延迟或数据处理时间
  }, 500); // 防抖等待时间为500毫秒   


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number,row?:any) => {
  formRef.value.open(type, id,row)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RelationshipApi.deleteRelationship(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RelationshipApi.exportRelationship(queryParams)
    download.excel(data, '物料供应商关联.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 加载产品、仓库列表、供应商
  // const supplierData = await ProductApi.getProductSimpleList()
  // supplierList.value = handleTree(supplierData, 'id')
  // porductList = Object.assign(supplierData);
}) 
</script>